package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.SystemParamMapper;
import org.linlinjava.litemall.db.domain.SystemParam;
import org.linlinjava.litemall.db.domain.SystemParamExample;
import org.linlinjava.litemall.db.util.Str;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class SystemParamService {
    @Autowired
    private SystemParamMapper mapper;

    public List<SystemParam> list(String code, Integer page, Integer limit) {
        SystemParamExample.Criteria query = getQuery();
        if (!Str.isEmpty(code)) {
            query.andCodeLike(code);
        }
        PageHelper.startPage(page, limit);
        List<SystemParam> res = mapper.selectByExample(query.example());
        return res;
    }


    public Boolean delete(Integer id){
        mapper.logicalDeleteByPrimaryKey(id);
        return true;
    }

    public String save(SystemParam systemParam) {
        String code = systemParam.getCode();
        Integer id = systemParam.getId();
        if(id == null){
            if (Str.isEmpty(code)) {
                return "code不能为空";
            }
            SystemParamExample.Criteria criteria = getQuery().andCodeEqualTo(code);
            List<SystemParam> list = mapper.selectByExample(criteria.example());
            if (list != null && list.size() > 0)
                return "code在数据库中已经存在";
            systemParam.setAddTime(LocalDateTime.now());
            mapper.insert(systemParam);
        }else{
            SystemParam old = mapper.selectByPrimaryKey(id);
            if(old == null)
                return "记录不存在";
            old.setDeleted(Boolean.FALSE);
            old.setDetail(systemParam.getDetail());
            old.setValue(systemParam.getValue());
            mapper.updateByPrimaryKey(old);
        }
        return null;
    }

    private SystemParamExample.Criteria getQuery() {
        SystemParamExample example = new SystemParamExample();
        return example.createCriteria();
    }
}
